from django.db import connection

from libs.db import DB


def query_goods_class_name(class_id):
    class_name = ''
    try:
        with connection.cursor() as cursor:
            sql = 'select class_name from table_goods_class where id=%s'
            cursor.execute(sql, class_id)
            row = cursor.fetchone()
            if row is not None:
                class_name = row[0]
    except Exception as e:
        print(e)
    return class_name


def get_children_by_pid(pid, cursor):
    db = DB('table_goods_class', conn=cursor)
    rows = db.find(['id'], 'parent_id=%s', [pid])
    s_arr = []
    for row in rows:
        s_arr.append(str(row.get('id')))
    return ','.join(s_arr)


def query_class_dict_by_ids(cursor, ids):
    db = DB('table_goods_class', conn=cursor)
    rows = db.find(['id', 'class_name'], 'id in ({})'.format(ids))
    md = {}
    for row in rows:
        class_id = row.get('id')
        class_name = row.get('class_name')
        md.update({class_id: class_name})
    return md
